package cn.work.control;

import cn.work.bean.reservationBean;
import cn.work.service.ReservationService;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "searchReservationsServlet", value = "/searchReservationsServlet")
public class searchReservationsServlet extends HttpServlet {
    private ReservationService reservationService = new ReservationService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String search = request.getParameter("query");
        List<reservationBean> resultList;
        try {
            resultList = reservationService.searchReservations(search);
            System.out.println(resultList);
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
        Gson gson = new Gson();
        PrintWriter out = response.getWriter();
        if (resultList != null && !resultList.isEmpty()) {
            String json = gson.toJson(resultList);
            System.out.println("响应内容: " + json);
            out.write(json);
            out.flush();
            out.close();
        } else {
            String json = gson.toJson("没有找到相关预定");
            out.write(json);
            out.flush();
            out.close();
        }
    }
}
